package cn.xxm.scene.config.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.UUID;


/**
 * @program: scene-rule
 * @link: 55864455@qq.com
 * @author: Mr.Xxm
 * @create: 2020-08-30 15:00
 **/
@Component
@ConditionalOnProperty(name = {"ff.mb.rabbit.dead.letter.exchange.switch"}, havingValue = "true", matchIfMissing = false)
@Slf4j
public class DeadLetterRabbitMQProducer  {

    @Value("${ff.mb.rabbit.delay.jetco.exchange}")
    private String delayExchangeName;

    @Value("${ff.mb.rabbit.delay.routingkey}")
    private String delayRoutingkey;

    @Value("${ff.mb.rabbit.delay.jetco.bindingKey}")
    private String delayBindingkey;

    @Value("${ff.mb.rabbit.delay.jetco.timeout}")
    private String timeout;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    public void sendMsg(Object msg, CorrelationData correlationData){
        rabbitTemplate.convertAndSend(delayExchangeName,delayRoutingkey,msg,message ->{
            message.getMessageProperties().setExpiration(timeout);
            log.info("msg:{} 延时时间timeout:{}", JSONObject.toJSONString(msg),timeout);
            return message;
        },correlationData);
    }


    /**
     * 功能描述:
     * @param: 发送MQ消息
     * @return:
     * @author:
     * @date: 2020/8/30 15:12
     */
    public boolean sendMsg(MQMessageDTO mqMessageDTO){
        String reference = mqMessageDTO.getReference();

        try {
            log.info(">>>发送MQ消息:{}", JSONObject.toJSONString(mqMessageDTO));
            CorrelationData correlationData = new CorrelationData(reference);
            sendMsg(mqMessageDTO,correlationData);
            return true;
        } catch (Exception e) {
            log.error("发送消息异常",e);
            return false;
        }
    }

}
